package com.cruise.game.security.handler;

import com.alibaba.fastjson2.JSON;
import com.cruise.game.common.api.ApiCode;
import com.cruise.game.common.api.ApiResult;
import com.cruise.game.common.constants.CommonConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义认证入口点
 *
 * @author cruise
 * @date 2025-02-28
 */
@Slf4j
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException {
        log.error("认证失败: {}", e.getMessage());
        
        response.setContentType(CommonConstants.CONTENT_TYPE_JSON);
        response.setCharacterEncoding(CommonConstants.UTF8);
        response.getWriter().write(JSON.toJSONString(ApiResult.fail(ApiCode.UNAUTHORIZED, "请先登录")));
    }
}
